<template>
  <el-drawer v-model="visible" 
  :title="isEdit ? '编辑教师' : '添加教师'" 
  direction="rtl" size="500px"
  :before-close="handleClose"
  class="teacher-form-drawer"
  >

  <!-- 自定义头部 -->
    <template #header="{ titleId, titleClass }">
      <div class="drawer-header">
        <div class="header-icon">
          <el-icon size="24">
            <User v-if="isEdit" />
            <Plus v-else />
          </el-icon>
        </div>
        <div class="header-content">
          <h3 :id="titleId" :class="titleClass">
            {{ isEdit ? '编辑教师' : '添加教师' }}
          </h3>
          <p class="header-subtitle">
            {{ isEdit ? '修改教师信息' : '创建新的教师账户' }}
          </p>
        </div>
      </div>
    </template>

    <div class="drawer-content">
      <el-form ref="formRef" 
      :model="formData" 
      :rules="formRules" 
      label-width="100px" 
      label-position="top"
      class="enhanced-form">
        <!-- 基本信息 -->
        <div class="form-section">
          <h4 class="section-title">基本信息</h4>
          <div class="form-row">
            <el-form-item label="工号" prop="teacherId" class="form-item-enhanced">
              <el-input v-model="formData.teacherId" placeholder="请输入教师工号（如：T2023001）" class="enhanced-input">
                <template #prefix>
                  <el-icon class="input-icon"><User /></el-icon>
                </template>
              </el-input>
            </el-form-item>

            <el-form-item label="姓名" prop="name" class="form-item-enhanced">
              <el-input v-model="formData.name" placeholder="请输入教师姓名" class="enhanced-input">
                <template #prefix>
                  <el-icon class="input-icon"><Edit /></el-icon>
                </template>
              </el-input>
            </el-form-item>
          </div>

          <div class="form-row">
            <el-form-item label="性别" prop="gender" class="form-item-enhanced">
              <el-radio-group v-model="formData.gender" class="enhanced-radio-group">
                <el-radio label="男" class="enhanced-radio">男</el-radio>
                <el-radio label="女" class="enhanced-radio">女</el-radio>
              </el-radio-group>
            </el-form-item>

            <el-form-item label="职称" prop="title" class="form-item-enhanced">
              <el-select v-model="formData.title" placeholder="请选择职称" class="enhanced-select">
                <el-option label="教授" value="教授" />
                <el-option label="副教授" value="副教授" />
                <el-option label="讲师" value="讲师" />
                <el-option label="助教" value="助教" />
              </el-select>
            </el-form-item>
          </div>
        </div>

        <!-- 院系信息 -->
        <div class="form-section">
          <h4 class="section-title">院系信息</h4>
          <el-form-item label="所属院系" prop="department" class="form-item-enhanced">
            <el-select v-model="formData.department" placeholder="请选择院系" class="enhanced-select">
              <el-option label="计算机学院" value="计算机学院" />
              <el-option label="软件学院" value="软件学院" />
              <el-option label="数学学院" value="数学学院" />
              <el-option label="物理学院" value="物理学院" />
              <el-option label="化学学院" value="化学学院" />
            </el-select>
          </el-form-item>

          <el-form-item label="任教科目" prop="coursesTaught" class="form-item-enhanced">
            <el-select v-model="formData.coursesTaught" multiple placeholder="请选择任教科目" class="enhanced-select multiple">
              <el-option label="数据结构" value="数据结构" />
              <el-option label="算法设计" value="算法设计" />
              <el-option label="软件工程" value="软件工程" />
              <el-option label="项目管理" value="项目管理" />
              <el-option label="操作系统" value="操作系统" />
              <el-option label="计算机网络" value="计算机网络" />
              <el-option label="数据库原理" value="数据库原理" />
              <el-option label="编译原理" value="编译原理" />
            </el-select>
            <div class="form-tip">可多选任教科目</div>
          </el-form-item>
        </div>

        <!-- 联系信息 -->
        <div class="form-section">
          <h4 class="section-title">联系信息</h4>
          <div class="form-row">
            <el-form-item label="联系电话" prop="phone" class="form-item-enhanced">
              <el-input v-model="formData.phone" placeholder="请输入联系电话" class="enhanced-input">
                <template #prefix>
                  <el-icon class="input-icon"><Phone /></el-icon>
                </template>
              </el-input>
            </el-form-item>

            <el-form-item label="邮箱" prop="email" class="form-item-enhanced">
              <el-input v-model="formData.email" placeholder="请输入邮箱地址" class="enhanced-input">
                <template #prefix>
                  <el-icon class="input-icon"><Message /></el-icon>
                </template>
              </el-input>
            </el-form-item>
          </div>
        </div>

        <!-- 状态信息 -->
        <div class="form-section">
          <h4 class="section-title">状态信息</h4>
          <div class="form-row">
            <el-form-item label="入职时间" prop="hireDate" class="form-item-enhanced">
              <el-date-picker v-model="formData.hireDate" type="date" placeholder="选择入职时间" class="enhanced-date-picker" />
            </el-form-item>

            <el-form-item label="账户状态" prop="status" class="form-item-enhanced">
              <el-radio-group v-model="formData.status" class="enhanced-radio-group">
                <el-radio label="在职" class="enhanced-radio status-active">在职</el-radio>
                <el-radio label="离职" class="enhanced-radio status-inactive">离职</el-radio>
              </el-radio-group>
            </el-form-item>
          </div>
        </div>

        <!-- 备注 -->
        <div class="form-section">
          <h4 class="section-title">其他信息</h4>
          <el-form-item label="备注" class="form-item-enhanced">
            <el-input v-model="formData.remark" type="textarea" :rows="3" placeholder="请输入备注信息" class="enhanced-textarea" />
          </el-form-item>
        </div>
      </el-form>
    </div>

    <template #footer>
      <div class="drawer-footer">
        <el-button @click="handleClose" class="cancel-btn">
          <el-icon><Close /></el-icon>
          取消
        </el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitting" class="submit-btn">
          <el-icon><Check /></el-icon>
          {{ isEdit ? '更新' : '添加' }}
        </el-button>
      </div>
    </template>
  </el-drawer>
</template>

<script setup>
import { ref, reactive, computed, watch, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { User, Phone, Message, Plus, Close, Check, Edit } from '@element-plus/icons-vue'
import { postJson,get } from '@/axios'

// Props
const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  teacherData: {
    type: Object,
    default: () => ({})
  },
  isEdit: {
    type: Boolean,
    default: false
  }
})

// Emits
const emit = defineEmits(['update:visible', 'submit'])

// 响应式数据
const formRef = ref()
const submitting = ref(false)

// 表单数据
const defaultFormData = {
  id: null,
  teacherId: '',
  name: '',
  gender: '',
  department: '',
  title: '',
  coursesTaught: [],
  phone: '',
  email: '',
  hireDate: '',
  status: '在职',
  avatar: '',
  remark: ''
}

const formData = reactive({ ...defaultFormData })

// 表单验证规则
const formRules = computed(() => {
  return {
    teacherId: [
      { required: true, message: '请输入教师工号', trigger: 'blur' },
      { pattern: /^T\d{7}$/, message: '工号格式应为T+7位数字', trigger: 'blur' },
      {
        validator: (rule, value, callback) => {
          if (!value) {
            callback()
            return
          }
          // 编辑模式下，如果工号没变化，不需要检查
          if (props.isEdit && value === props.teacherData?.teacherId) {
            callback()
            return
          }
          
          checkFieldUnique('teacherId', value, props.isEdit ? formData.id : null)
            .then(isUnique => {
              if (isUnique) {
                callback()
              } else {
                callback(new Error('工号已被其他教师使用'))
              }
            })
            .catch(() => {
              callback(new Error('检查工号唯一性失败'))
            })
        },
        trigger: 'blur'
      }
    ],
    name: [
      { required: true, message: '请输入教师姓名', trigger: 'blur' },
      { min: 2, max: 20, message: '姓名长度在 2 到 20 个字符', trigger: 'blur' }
    ],
    gender: [
      { required: true, message: '请选择性别', trigger: 'change' }
    ],
    department: [
      { required: true, message: '请选择院系', trigger: 'change' }
    ],
    title: [
      { required: true, message: '请选择职称', trigger: 'change' }
    ],
    coursesTaught: [
      { required: true, message: '请选择任教科目', trigger: 'change' }
    ],
    phone: [
      { required: true, message: '请输入联系电话', trigger: 'blur' },
      { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' },
      {
        validator: (rule, value, callback) => {
          if (!value) {
            callback()
            return
          }
          // 编辑模式下，如果手机号没变化，不需要检查
          if (props.isEdit && value === props.teacherData?.phone) {
            callback()
            return
          }
          
          checkFieldUnique('phone', value, props.isEdit ? formData.id : null)
            .then(isUnique => {
              if (isUnique) {
                callback()
              } else {
                callback(new Error('手机号已被其他教师使用'))
              }
            })
            .catch(() => {
              callback(new Error('检查手机号唯一性失败'))
            })
        },
        trigger: 'blur'
      }
    ],
    email: [
      { required: true, message: '请输入邮箱地址', trigger: 'blur' },
      { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' },
      {
        validator: (rule, value, callback) => {
          if (!value) {
            callback()
            return
          }
          // 编辑模式下，如果邮箱没变化，不需要检查
          if (props.isEdit && value === props.teacherData?.email) {
            callback()
            return
          }
          
          checkFieldUnique('email', value, props.isEdit ? formData.id : null)
            .then(isUnique => {
              if (isUnique) {
                callback()
              } else {
                callback(new Error('邮箱已被其他教师使用'))
              }
            })
            .catch(() => {
              callback(new Error('检查邮箱唯一性失败'))
            })
        },
        trigger: 'blur'
      }
    ],
    hireDate: [
      { required: true, message: '请选择入职时间', trigger: 'change' }
    ],
    status: [
      { required: true, message: '请选择账户状态', trigger: 'change' }
    ]
  }
})

// 计算属性
const visible = computed({
  get() {
    return props.visible
  },
  set(value) {
    emit('update:visible', value)
  }
})

// 监听器
watch(() => props.visible, (newVal) => {
  if (newVal) {
    if (props.isEdit && props.teacherData) {
      // 编辑模式，填充数据
      Object.assign(formData, {
        ...defaultFormData,
        ...props.teacherData,
        coursesTaught: typeof props.teacherData.coursesTaught === 'string' 
          ? props.teacherData.coursesTaught.split(',') 
          : props.teacherData.coursesTaught,
        status: formData.status === '在职' ? true : false
      })
    } else {
      // 新增模式，重置表单
      Object.assign(formData, defaultFormData)
    }

    // 重置表单验证
    nextTick(() => {
      formRef.value?.clearValidate()
    })
  }
})

//添加检查唯一性的方法
const checkFieldUnique = async (field, value, excludeId) => {
  try {
    const response = await get('/umsTeacher/checkUnique', {
      field,
      value,
      excludeId
    })
    return !response // 如果返回true表示被占用，false表示可用
  } catch (error) {
    console.error('检查唯一性失败:', error)
    return false
  }
}


const handleSubmit = async () => {
  try {
    await formRef.value.validate();
    submitting.value = true;

    // 准备提交数据
    const submitData = {
      ...formData,
      hireDate: formData.hireDate ? formatDate(formData.hireDate) : formatDate(new Date()),
      coursesTaught: Array.isArray(formData.coursesTaught) 
        ? formData.coursesTaught.join(',') 
        : formData.coursesTaught,
      status: formData.status === '在职' // 转换为后端需要的布尔值
    };

    // 调用不同的API
    const apiUrl = props.isEdit 
      ? `/umsTeacher/updateById/${formData.id}` 
      : '/umsTeacher/save';
    
    const response = await postJson(apiUrl, submitData);

    emit('submit');
    ElMessage.success(props.isEdit ? '教师信息更新成功' : '教师添加成功');
    handleClose();
  } catch (error) {
    console.error('表单提交失败:', error);
    ElMessage.error('操作失败: ' + (error.response?.data?.message || error.message));
  } finally {
    submitting.value = false;
  }
};

const handleClose = () => {
  emit('update:visible', false)
}

// 日期格式化辅助函数
const formatDate = (date) => {
  if (!date) return ''
  const d = new Date(date)
  const year = d.getFullYear()
  const month = String(d.getMonth() + 1).padStart(2, '0')
  const day = String(d.getDate()).padStart(2, '0')
  return `${year}-${month}-${day}`
}
</script>

<style scoped lang="scss">
// 添加sass模块引用
@use "sass:color";

// 颜色定义
$primary-color: #6E82EE;
$secondary-color: #B2CBF0;
$accent-color: #FEEAB3;
$light-bg: #f8fafc;
$dark-text: #1f2937;
$gray-text: #6b7280;

// 抽屉整体样式
.teacher-form-drawer {
  height: 100%;
  display: flex;
  flex-direction: column;

  :deep(.el-drawer) {
    border-radius: 16px 0 0 16px;
    box-shadow: -12px 0 40px rgba(110, 130, 238, 0.15);
    background: white;
    display: flex;
    flex-direction: column;
  }

  // 自定义头部
  .drawer-header {
    padding: 16px 20px;
    background: linear-gradient(135deg, $primary-color 0%, color.scale($primary-color, $lightness: 10%) 100%);
    color: white;
    flex-shrink: 0;
    border-radius: 16px 极好的0 0 0;

    h3 {
      margin: 0;
      font-size: 18px;
      font-weight: 600;
    }

    .header-subtitle {
      margin: 4px 0 0;
      font-size: 13px;
      color: rgba(255, 255, 255, 0.85);
    }
  }

  // 内容区域
  .drawer-content {
    flex: 1;
    padding: 16px;
    overflow-y: auto;
    display: grid;
    grid-template-columns: 1fr;
    gap: 12px;

    // 表单行
    .form-row {
      display: grid;
      grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
      gap: 12px;
      align-items: start;
    }

    // 表单项
    .form-item-enhanced {
      margin-bottom: 12px;

      :deep(.el-form-item__label) {
        font-weight: 500;
        color: $dark-text;
        margin-bottom: 6px;
        font-size: 13px;
      }
    }
  }

  // 输入框样式
  .enhanced-input {
    :deep(.el-input__wrapper) {
      border-radius: 8px;
      border: 1px solid #e5e7eb;
      box-shadow: none;
      padding: 0 12px;
      height: 36px;
      transition: all 0.2s ease;

      &:hover {
        border-color: $secondary-color;
      }

      &.is-focus {
        border-color: $primary-color;
        box-shadow: 0 0 0 2px rgba($primary-color, 0.1);
      }

      .input-icon {
        color: $primary-color;
        margin-right: 8px;
        font-size: 16px;
      }
    }
  }

  // 选择器样式
  .enhanced-select {
    :deep(.el-select极好的__wrapper) {
      border-radius: 8px;
      border: 1px solid #e5e7eb;
      box-shadow: none;
      padding: 0 12px;
      min-height: 36px;
      transition: all 0.2s ease;

      &:hover {
        border-color: $secondary-color;
      }

      &.is-focus {
        border-color: $primary-color;
        box-shadow: 0 0 0 2px rgba($primary-color, 0.1);
      }
    }

    &.multiple {
      :deep(.el-select__wrapper) {
        padding: 4px 12px;

        .el-select__tags {
          .el-tag {
            background: linear-gradient(135deg, $primary-color 0%, color.scale($primary-color, $lightness: 10%) 100%);
            border: none;
            color: white;
            border-radius: 6px;
            font-size: 12px;
            padding: 4px 8px;
            margin: 2px;
          }
        }
      }
    }
  }

  // 单选框样式
  .enhanced-radio-group {
    display: flex;
    gap: 16px;
    align-items: center;
    height: 36px;

    .enhanced-radio {
      :deep(.el-radio__inner) {
        border-color: #e5e7eb;
        width: 16px;
        height: 16px;

        &:hover {
          border-color: $primary-color;
        }

        &::after {
          width: 6px;
          height: 6px;
          background: $primary-color;
        }
      }

      :deep(.el-radio__label) {
        color: $dark-text;
        font-size: 13px;
      }

      &.status-active {
        :deep(.el-radio__input.is-checked .el-radio__inner) {
          background-color: #10b981;
          border-color: #10b981;
        }
      }

      &.status-inactive {
        :deep(.极好的el-radio__input.is-checked .el-radio__inner) {
          background-color: #ef4444;
          border-color: #ef4444;
        }
      }
    }
  }

  // 文本域样式
  .enhanced-textarea {
    :deep(.el-textarea__inner) {
      border-radius: 8px;
      border: 1px solid #e5e7eb;
      padding: 8px 12px;
      font-size: 13px;
      min-height: 80px;
    }
  }

  // 底部按钮
  .drawer-footer {
    padding: 12px 16px;
    background: white;
    border-top: 1px solid #f3f4f6;
    display: flex;
    justify-content: flex-end;
    gap: 12px;
    flex-shrink: 0;

    .cancel-btn {
      background: #f9fafb;
      border: 1px solid #e5e7eb;
      color: $gray-text;
      border-radius: 6px;
      padding: 8px 16px;
      font-size: 13px;
      height: 36px;

      &:hover {
        background: #f3f4f6;
      }
    }

    .submit-btn {
      background: linear-gradient(135deg, $primary-color 0%, color.scale($primary-color, $lightness: 5%) 100%);
      border: none;
      border-radius: 6px;
      padding: 8px 20px;
      font-size: 13px;
      height: 36px;
      box-shadow: 0 2px 6px rgba($primary-color, 0.2);

      &:hover {
        background: linear-gradient(135deg, color.scale($primary-color, $lightness: -5%) 0%, $primary-color 100%);
      }
    }
  }

  // 响应式设计
  @media (max-width: 768px) {
    .drawer-content {
      padding: 12px;

      .form-row {
        grid-template-columns: 1fr;
      }
    }

    .drawer-footer {
      padding: 12px;
      flex-direction: column-reverse;

      .cancel-btn, .submit-btn {
        width: 100%;
      }
    }
  }
}
</style>

